<?php

namespace App\Http\Controllers\Order;

use App\Http\Controllers\BaseController;
use App\Http\Validate\Order\Returnordersub;
use App\Models\Order\Outboundorder;
use App\Models\Order\Outboundordersub;
use App\Models\Order\Outboundordersubsub;
use App\Models\Order\Returnorder as ModelReturnorder;
use App\Models\Order\Returnordersub as ModelReturnordersub;
use App\Models\Stock\Stock as ModelStock;
use App\Models\Stock\StockSub;
use App\Services\Balance\Balance;
use App\Services\Common\SnCode;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 退货单模块
 * 产品经理端审核
 */
class ReturnorderController extends BaseController
{
    /**
     * 退货
     *
     * 退货逻辑修改；原退货逻辑传入 出库单id suborder,每次退一个出库单的 多个子订单，可拆分退货
     *
     * 新逻辑为 勾选多个子订单，进行退货,退完整的子订单
     *
     *
     */
    public function dopostadd(Request $request)
    {
//        $id = $request['id'];
//        $one = ModelOutboundorder::where('id', $id)->first();
//        if (!$one) {
//            return response()->json(['code' => '001', 'msg' => '订单不存在']);
//        } else {
//            $one = $one->toArray();
//        }
        $ids = $request['ids']; //出库子订单id集合
        if(empty($ids)){
            return response()->json(['code'=>'001','msg'=>'退货子订单不能为空']);
        }
        if(!is_array($ids)){
            $ids = explode(',',$ids);
        }
        $mangerinfo = $this->mangerinfo;
        $cpid = $mangerinfo['cpid'] ?? 0;
        $manger_id = $mangerinfo['id'] ?? 0;
        $manger_name = $mangerinfo['realname'] ?? 0;

        $returnOrderSub = ModelReturnordersub::where('cpid',$cpid)->whereIn('outbound_order_sub_id',$ids)->where('return_status','<>','5')->get();
        if(!$returnOrderSub->isEmpty()){
            return response()->json(['code' => '001', 'msg' => '退货单已存在']);
        }
        DB::beginTransaction();
        try {
            $outboundordersub = Outboundordersub::whereIn('id',$ids)->get();
            if($outboundordersub){
                $outboundordersub = $outboundordersub->toArray();
            }else{
                $outboundordersub = [];
            }
            $pids = array_unique(array_column($outboundordersub,'p_id'));
            $outboundInfos = Outboundorder::whereIn('id',$pids)->get();
            foreach ($outboundInfos as $outboundInfo) {
                //生成退货单
                $data = [
                    'cpid' => $cpid,
                    'manger_id' => $manger_id,
                    'manger_name' => $manger_name,
                    'order_number' => $outboundInfo['order_number'],
                    'document_number' => SnCode::getSnCode('TH_'),
                    'document_date' => $outboundInfo['document_date'],
                    'bill_type' => $outboundInfo['bill_type'],
                    'business_type' => $outboundInfo['business_type'],
                    'custom_id' => $outboundInfo['custom_id'],
                    'custom_name' => $outboundInfo['custom_name'],
                    'settlement_company' => $outboundInfo['settlement_company'],
                    'wagon_number' => $outboundInfo['wagon_number'] ?? '',
                    'driver_phone_number' => $outboundInfo['driver_phone_number'] ?? '',
                    'warehouse_return_order' => $outboundInfo['warehouse_return_order'],
                    'outbound_order_id' => $outboundInfo['id'],
                    'remark' => $outboundInfo['remark'] ?? '',
                    'create_at' => time(),
                ];
                //父级退货单
                $p_id = ModelReturnorder::create($data)->id;

                $data_sub = [];
                foreach ($outboundordersub as $sub_item){
                    //父级子订单
                    if($sub_item['p_id'] == $outboundInfo['id']){
                        //孙订单信息
                        $grandson_order = Outboundordersubsub::where('p_id',$sub_item['id'])->get();
                        if($grandson_order){
                            $grandson_order = $grandson_order->toArray();
                        }else{
                            $grandson_order = [];
                        }
                        $data_sub = [
                            'cpid' => $cpid,
                            'manger_id' => $manger_id,
                            'material_id' => $sub_item['material_id'],
                            'stock_id' => $sub_item['stock_id'],
                            'archive_no' => $sub_item['archive_no'],
                            'warehouse_name' => $sub_item['warehouse_name'],
                            'steel_factory_name' => $sub_item['steel_factory_name'],
                            'archive_type' => $sub_item['archive_type'],
                            'archive_name' => $sub_item['archive_name'],
                            'archive_spec' => $sub_item['archive_spec'],
                            'archive_material' => $sub_item['archive_material'],
                            'breed_name' => $sub_item['breed_name'],
                            'weight' => $sub_item['weight'],
                            'pieces' => $sub_item['pieces'],
                            'length' => $sub_item['length'],
                            'unit_price' => $sub_item['unit_price'],
                            'total' => $sub_item['total'],
                            'accrual' => $sub_item['accrual'] ?? '',
                            'performance' => $sub_item['performance'] ?? '',
                            'remark' => $sub_item['remark'] ?? '',
                            'suborder' => json_encode($grandson_order, true),
                            'outbound_order_sub_id' => $sub_item["id"],
                            'create_at' => time(),
                            'p_id' => $p_id
                        ];
                        ModelReturnordersub::create($data_sub);
                    }
                }
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '退货失败' . $e->getMessage()]);
        }

        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 列表
     */
    public function getlist(Request $request)
    {
        $memberinfo = $this->mangerinfo;
        $isgetall = $request->isgetall ?? 0;
        $list = ModelReturnorder::getList($request, $memberinfo, $isgetall);
        if ($list['list']) foreach ($list['list'] as $key => $value) {
            foreach ($value['suborder'] as $k => $v) {
                $list['list'][$key]['suborder'][$k]['weight'] = mathfuncweight('div', $v['weight'], 10000, 4);
                $list['list'][$key]['suborder'][$k]['unit_price'] = mathfuncmoney('div', $v['unit_price'], 100, 2);
                $list['list'][$key]['suborder'][$k]['total'] = mathfuncmoney('div', $v['total'], 100, 2);
                $list['list'][$key]['suborder'][$k]['accrual'] = mathfuncmoney('div', $v['accrual'], 100, 2);
                $list['list'][$key]['suborder'][$k]['performance'] = mathfuncmoney('div', $v['performance'], 100, 2);

                $list['list'][$key]['suborder'][$k]['suborder'] = json_decode($v['suborder']);
            }
        }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    /**
     * 详情
     */
    public function getone(Request $request)
    {
        $id = $request->id ?? 0;
        $one = ModelReturnorder::getone($id);
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        }
        $one = $one->toArray();
        if ($one['suborder']) foreach ($one['suborder'] as $key => $value) {
            $one['suborder'][$key]['weight'] = mathfuncweight('div', $value['weight'], 10000, 4);
            $one['suborder'][$key]['unit_price'] = mathfuncmoney('div', $value['unit_price'], 100, 2);
            $one['suborder'][$key]['total'] = mathfuncmoney('div', $value['total'], 100, 2);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $one]);
    }

    /**
     * 产品经理端，处理退货子订单
     */
    public function handlereturn(Request $request)
    {
        //校验
        $params = ['id', 'return_status'];
        $req_data = $request->only($params);
        $validate = new Returnordersub('handlereturn');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }

        // 退货子订单id
        $id = $req_data['id'];
        $one = ModelReturnordersub::where('id', $id)->first();
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '子订单不存在']);
        }

        $data = [
            'return_status' => $req_data['return_status'],
            'update_at' => time()
        ];
        ModelReturnordersub::where('id', $id)->update($data);

        if ($req_data['return_status'] == 4) {
            $one = $one->toArray();

            ModelStock::where([
                'id' => $one['stock_id']
            ])->update([
                'current_pieces' => DB::raw('current_pieces + ' . $one['pieces']),
                'current_weight' => DB::raw('current_weight + ' . $one['weight']),
                'can_use_pieces' => DB::raw('can_use_pieces + ' . $one['pieces']),
                'can_use_weight' => DB::raw('can_use_weight + ' . $one['weight']),
                // 'locked_pieces' => DB::raw('locked_pieces - ' . $one['pieces']),
                // 'locked_weight' => DB::raw('locked_weight - ' . mathfuncweight('mul', $one['weight'], 10000)),
            ]);
            //子库存数据
            $suborders = json_decode($one['suborder'],true);
            if ($suborders)
            {
                foreach ($suborders as $suborder)
                {
                    /****
                     *  出库子库存钢材
                     */
                    StockSub::where(['id'=>$suborder['stock_sub_id']])->update(
                        [

                            'current_pieces' => DB::raw('current_pieces + ' . $suborder['pieces']),
                            'current_weight' => DB::raw('current_weight + ' . $suborder['weight']),
                            'can_use_weight' => DB::raw('can_use_weight + ' . $suborder['weight']),
                            'can_use_pieces' => DB::raw('can_use_pieces + ' . $suborder['pieces']),
                        ]
                    );

                }
            }

            $ReturnOrder = ModelReturnorder::where('id',$one['p_id'])->first();
            Balance::SaleRefund($ReturnOrder['custom_id'],$ReturnOrder['cpid'],$one['total'],$ReturnOrder['manger_id'],3);
        }

        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 释放 父子库存,可用重量件数，现存重量件数
     *
     *
     */
    public static function release_stock($data = []){
//        if(empty($data) || empty($data["scene"]) || empty($data["data"])){
//            return false;
//        }
//        if($data["scene"] == "outbound"){
//            foreach ($data["data"] as $item){
//
//
//
//            }
//        }
    }
}
